//
//  AMOAuthViewController.m
//  AMwb
//
//  Created by zhc on 15/12/1.
//  Copyright © 2015年 zhc. All rights reserved.
//

#import "AMOAuthViewController.h"
#import "AFNetworking.h"
#import "AMNewFeatureController.h"
#import "AMTabBarViewController.h"
#import  "MBProgressHUD+PKX.h"
#import "AMAccountTool.h"

#import "AMAccount.h"


@interface AMOAuthViewController()<UIWebViewDelegate>

@end

@implementation AMOAuthViewController



- (void)viewDidLoad{
    [super viewDidLoad];
    
    //创建webView
    UIWebView *webView=[[UIWebView alloc]init];
    webView.frame=self.view.bounds;
    
    webView.delegate=self;
    [self.view addSubview:webView];
    //登陆页面
    //https://www.baidu.com
    //client_id=4097602553
    NSURL *url=[NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=4097602553&redirect_uri=https://www.baidu.com"];
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    
    
    
    
    [webView loadRequest:request];
    
    
    
    
    

}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //完成
    [MBProgressHUD hideHUD];


}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
   //加载失败
    [MBProgressHUD hideHUD];
}

- (void)webViewDidStartLoad:(UIWebView *)webView{

    [MBProgressHUD showMessage:@"正在加载数据1...."];

}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    AMLog(@"---%@",request.URL.absoluteURL);
    // AMLog(@"---%@",request.URL.absoluteString);
    //    https://www.baidu.com/?code=41d2c3d6298d52d83a3c91af70ca6343
    //2015-12-01 16:08:41.578 AMwb[6493:152382] ---https://www.baidu.com/?code=ee1cd77a6e388fc0b831239d14549af1

    
    //1.获得url
    NSString *url=request.URL.absoluteString;
    //2.判断是否是回调地址
    NSRange range=[url rangeOfString:@"code="];
    if(range.length !=0){//是回调地址
        
        
      NSUInteger fromIndex = range.location+range.length;//23+5 从=后面开始
      
      //获得了code
      NSString *code = [url substringFromIndex:fromIndex];
    AMLog(@"%@--code=",code);
        
        //利用code换取一个accessToken
        
        
        [self accesTokenWithCode:code];
        
        return NO;
    
    }
    
    
   
    
    
    return YES;

}

/*
 https://api.weibo.com/oauth2/access_token
 
 
 必选	类型及范围	说明
 client_id=4097602553	   true	string	申请应用时分配的AppKey。
 client_secret 4f973e5b24a2ae2087103844b2205076 	true	string	申请应用时分配的AppSecret。
 grant_type	true authorization_codestring	请求的类型，填写authorization_code
 
 grant_type为authorization_code时
 必选	类型及范围	说明
 code	true	   string	调用authorize获得的code值。
 redirect_uri	   true	string	回调地址，需需与注册应用里的回调地址一致。
 
 */

- (void)accesTokenWithCode:(NSString *)code{
  //请求管理者
    AFHTTPRequestOperationManager *mgr=[AFHTTPRequestOperationManager manager];
    
    //mgr.responseSerializer=[AFJSONRequestSerializer serializer];
    
    //拼接请求参数
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"client_id"]=@"4097602553";
    params[@"client_secret"]=@"4f973e5b24a2ae2087103844b2205076";
   // params[@"grant_type"]=@"authorization_code";
    params[@"grant_type"]=@"authorization_code";
    params[@"code"]=code;
    params[@"redirect_uri"]=@"https://www.baidu.com";
    
    
    
    //发送请求
    
    /*
     "access_token" = "2.00T6cBEClbH_TE051cc0467eufJ8aC";
     "expires_in" = 157679999;
         (过期) "remind_in" = 157679999;
     uid = 1891756987;
     
     
     */
    
    
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        
        [MBProgressHUD hideHUD];
        AMLog(@"su---%@",responseObject);
        
        
        //把得到的字典放到模型里面
        AMAccount *account=[AMAccount accountWithDict:responseObject];
        
        [AMAccountTool saveAccount:account];
        
//        
//        //将返回的账号数据存进去沙盒
//        NSString * doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//        NSString *path=[doc stringByAppendingPathComponent:@"account.plist"];
//      
//        
//        
//        
//        //把得到的字典放到模型里面
     //   AMAccount *account=[AMAccount accountWithDict:responseObject];
//        
//        
//     //自定义的对象存储 必须用NSkeyedArchiver ，没有什么writeToFile
//        
//        [NSKeyedArchiver archiveRootObject:account toFile:path];
        
        //[NSKeyedArchiver archiveRootObject:accout toFile:path];
      //[responseObject writeToFile:path atomically:YES];
        
      
        
         
        
       // [responseObject writeToFile:<#(nonnull NSString *)#> atomically:<#(BOOL)#>]
        //切换窗口根控制器
        
        
      //  [UIWindow switchrootVc];
        UIWindow *window=[UIApplication sharedApplication].keyWindow;
        
        [window switchrootVc];
        
        
        //  [AMAccountTool test];
//        
//        NSString *key=@"CFBundleVersion";
//        NSString *currentVerson =[NSBundle mainBundle].infoDictionary[key];
//        // NSLog(@"%@",[NSUserDefaults standardUserDefaults]);
//        //上一次的版本
//        NSString *lastKey=[[NSUserDefaults standardUserDefaults] objectForKey:key];
//        
//        
//        
//        UIWindow *window=[UIApplication sharedApplication].keyWindow;
//        
//        if ([lastKey isEqualToString: currentVerson]) {//一样的版本号，直接进入主页
//            window.rootViewController = [[AMTabBarViewController alloc]init];
//        }else{ //不一样的版本号，新特性
//            
//            window.rootViewController = [[AMNewFeatureController alloc]init];
//            
//            //将新的版本号放进沙盒
//            [[NSUserDefaults standardUserDefaults] setObject:currentVerson forKey:key];
//            [[NSUserDefaults standardUserDefaults] synchronize];//马上同步沙盒信息
//            
//        }
//        
//        
//        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        AMLog(@"fa---%@",error);
        
        [MBProgressHUD hideHUD];
    
    }];

    
   
    
    


}



@end
